package com.linkq.ipinyin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author wangpeng
 * @since 2025-06-29
 **/

@Service
@Slf4j
public class AppleReceiptVerifier {
    private static final String PRODUCTION_URL = "https://buy.itunes.apple.com/verifyReceipt";
    private static final String SANDBOX_URL = "https://sandbox.itunes.apple.com/verifyReceipt";

    private static final String SHARE_SECRET_KEY = "02cc6a64c5dd45dbab4c94ae38675793";

    public JSONObject verifyReceipt(String receiptData) {
        log.info(">>>>>>>>>>>>>>>>>>>> receiptData: {}", receiptData);
        log.info(">>>>>>>>>>>>>>>>>>>> sharedSecret: {}", SHARE_SECRET_KEY);
        RestTemplate restTemplate = new RestTemplate();

        JSONObject request = new JSONObject();
        request.put("receipt-data", receiptData);
        request.put("password", SHARE_SECRET_KEY);

        // 先尝试生产环境
        ResponseEntity<String> response = restTemplate.postForEntity(
                PRODUCTION_URL,
                request.toString(),
                String.class
        );

        JSONObject result = JSON.parseObject(response.getBody());
        log.info(">>>>>>>>>>>>>>>>>>>> verify result: {}", result.toString());
        int status = result.getIntValue("status");

        // 21007表示沙箱环境收据
        if (status == 21007) {
            response = restTemplate.postForEntity(
                    SANDBOX_URL,
                    request.toString(),
                    String.class
            );
            result = JSON.parseObject(response.getBody());
        }
        if (result.getIntValue("status") != 0) {
            throw new RuntimeException("Receipt verification failed: " + result);
        }
        return result;
    }
}
